package com.hag.equipment_server.netty.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.ByteOrder;

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    private  final ByteOrder BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
    //消息最大长度
    private  final int MAX_FRAME_LENGTH = 65535;
    //协议 帧长度描述 占几位
    private  final int LENGTH_FIELD_LENGTH = 4;
    //协议 帧长度描述 偏移位数
    private  final int LENGTH_FIELD_OFFSET = 1;
    private  final int LENGTH_ADJUSTMENT = -5;
    private  final int INITIAL_BYTES_TO_STRIP = 0;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //添加编解码
        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(BYTE_ORDER,MAX_FRAME_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_FIELD_LENGTH,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));
//        socketChannel.pipeline().addLast(new MyDecoder(BYTE_ORDER,MAX_FRAME_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_FIELD_LENGTH,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));
//        socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//        socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast(new MessageDecoder());
        socketChannel.pipeline().addLast(new NettyServerHandler());
    }
}